package com.youngjun.common.mybatis.autoconfigure;

import com.youngjun.common.mybatis.plugin.MybatisHelper;
import com.github.pagehelper.autoconfigure.PageHelperAutoConfiguration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 *
 * @author YoungJun
 */
@Configuration
@ConditionalOnBean(SqlSessionFactory.class)
@EnableConfigurationProperties(MybatisHelperProperties.class)
@AutoConfigureAfter(PageHelperAutoConfiguration.class)
public class MybatisHelperAutoConfiguration {

    @Autowired
    private List<SqlSessionFactory> sqlSessionFactoryList;

    @Autowired
    private MybatisHelperProperties properties;

    @PostConstruct
    public void addMybatisInterceptor() {
        if(properties.getEnabled()){
            MybatisHelper mybatisHelper = new MybatisHelper(properties);
            for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
                sqlSessionFactory.getConfiguration().addInterceptor(mybatisHelper);
            }
        }
    }

}
